package com.guojing.jl.myspring.demo.service;

import com.guojing.jl.myspring.demo.spring.BeanPostProcessor;
import com.guojing.jl.myspring.demo.spring.annotation.Compent;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @description:
 * @author: guojing
 * @create: 2023/4/20 21:35
 */
@Compent
public class MyBeanPostProcess implements BeanPostProcessor {
    @Override
    public Object postProcessBeforeInitialization(String beanName, Object bean) {

        System.out.println("MyBeanPostProcess-----postProcessBeforeInitialization----" +beanName);

        if("userService".equals(beanName)){
            Object instance = Proxy.newProxyInstance(MyBeanPostProcess.class.getClassLoader(), bean.getClass().getInterfaces(), new InvocationHandler() {
                @Override
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    System.out.println("模拟 " + beanName  + " aop-------------start-------");

                    Object invoke = method.invoke(bean, args);

                    System.out.println("模拟 " + beanName + " aop-------------end-------");

                    return invoke;
                }
            });
            return instance;
        }

        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(String beanName, Object bean) {
        System.out.println("MyBeanPostProcess-----postProcessAfterInitialization----" +beanName);
        return bean;
    }
}
